package com.tplan.tplanfontpageserver.service;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;

@Service
public class CompanyService {

    @Autowired
    RestTemplate restTemplate;

    // 设置超时熔断，加入缓存
    @CacheResult
    @HystrixCommand(fallbackMethod = "getCompanyByIdError", groupKey = "MemberGroup", commandKey = "MemberCommandKey", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")}, threadPoolProperties = {
            @HystrixProperty(name = "coreSize", value = "2")})
    public String getCompanyById(int id) {

        System.out.println("into getCompanyById(int id)");

        Map<String, String> params = new HashMap<>();

        params.put("id", String.valueOf(id));

        return restTemplate.getForEntity("http://EXTERNAL-SERVICE/company/get?id={id}", String.class, params).getBody();

    }

    public String getCompanyByIdError(int id) {
        return "hi," + id + ",sorry,error!";
    }

    @CacheRemove(commandKey = "MemberGroup")
    @HystrixCommand
    public void removeCache(Integer id) {

    }

}
